package com.wonyesoft.wuliu.acticity.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;

/**
 * @fileName FileUtils.java
 * @package com.immomo.momo.android.util
 * @description 文件工具类
 * @author 任东卫
 * @email 86930007@qq.com
 * @version 1.0
 */
public class FileUtils {
	/**
	 * 判断SD是否可以
	 * 
	 * @return
	 */
	public static boolean isSdcardExist() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return true;
		}
		return false;
	}

	/**
	 * 创建根目录
	 * 
	 * @param path
	 *            目录路径
	 */
	public static void createDirFile(String path) {
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
	}

	/**
	 * 创建文件
	 * 
	 * @param path
	 *            文件路径
	 * @return 创建的文件
	 */
	public static File createNewFile(String path) {
		File file = new File(path);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				return null;
			}
		}
		return file;
	}

	/**
	 * 删除文件夹
	 * 
	 * @param folderPath
	 *            文件夹的路径
	 */
	public static void delFolder(String folderPath) {
		delAllFile(folderPath);
		String filePath = folderPath;
		filePath = filePath.toString();
		java.io.File myFilePath = new java.io.File(filePath);
		myFilePath.delete();
	}

	/**
	 * 删除文件
	 * 
	 * @param path
	 *            文件的路径
	 */
	public static void delAllFile(String path) {
		File file = new File(path);
		if (!file.exists()) {
			return;
		}
		if (!file.isDirectory()) {
			return;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);
				delFolder(path + "/" + tempList[i]);
			}
		}
	}

	/**
	 * 获取文件的Uri
	 * 
	 * @param path
	 *            文件的路径
	 * @return
	 */
	public static Uri getUriFromFile(String path) {
		File file = new File(path);
		return Uri.fromFile(file);
	}

	/**
	 * 换算文件大小
	 * 
	 * @param size
	 * @return
	 */
	public static String formatFileSize(long size) {
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "未知大小";
		if (size < 1024) {
			fileSizeString = df.format((double) size) + "B";
		} else if (size < 1048576) {
			fileSizeString = df.format((double) size / 1024) + "K";
		} else if (size < 1073741824) {
			fileSizeString = df.format((double) size / 1048576) + "M";
		} else {
			fileSizeString = df.format((double) size / 1073741824) + "G";
		}
		return fileSizeString;
	}

	public static File createFileInSDCard(String dirPath, String name)
			throws Exception {
		File file = new File(dirPath, name);
		file.createNewFile();
		return file;
	}

	public static File createFileInSDCard(String name) throws Exception {
		int index = name.lastIndexOf(File.separator);
		String dir = name.substring(0, index);
		creatSDDir(dir);
		return createFileInSDCard(dir, name.substring(index + 1));
	}

	/**
	 * 创建新目录
	 */
	public static File creatSDDir(String dirPath) {
		File dirFile = new File(dirPath);
		if (!dirFile.exists())
			dirFile.mkdirs();
		return dirFile;
	}

	/**
	 * 判断文件存不存在
	 */
	public static boolean isFileExist(String name) {
		return new File(name).exists();
	}

	/**
	 * 将流转化成文件，写进内存卡
	 */
	public static File write2SDFromInput(String name, InputStream input) {
		if (input == null)
			return null;
		File file = null;
		try {
			file = createFileInSDCard(name);
			FileOutputStream output = new FileOutputStream(file);
			byte buffer[] = new byte[4 * 1024];
			int temp = -1;
			while ((temp = input.read(buffer)) != -1) {
				output.write(buffer, 0, temp);
			}
			output.flush();
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return file;
	}

	public static void deleteFile(String path) {
		if (path == null || "".equals(path))
			return;
		File file = new File(path);
		if (file.exists()) {
			file.delete();
		}
	}

	public static void deleteFile(File file) {
		if (file == null || !file.exists())
			return;
		file.delete();
	}

	private static final String TAG = "FileUtil";

	/**
	 * 根据文件路径 递归创建文件
	 * 
	 * @param file
	 */
	public static void createDipPath(String file) {
		String parentFile = file.substring(0, file.lastIndexOf("/"));
		File file1 = new File(file);
		File parent = new File(parentFile);
		if (!file1.exists()) {
			parent.mkdirs();
			try {
				file1.createNewFile();
				LogUtil.i(TAG, "Create new file :" + file);
			} catch (IOException e) {
				LogUtil.e(TAG, e.getMessage());
			}
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param path
	 */
	public static boolean deleteFile2(String path) {
		boolean bl;
		File file = new File(path);
		if (file.exists()) {
			bl = file.delete();
		} else {
			bl = false;
		}
		return bl;
	}

	/**
	 * 将bitmap保存到本地
	 * 
	 * @param mBitmap
	 * @param imagePath
	 */
	@SuppressLint("NewApi")
	public static void saveBitmap(Bitmap bitmap, String imagePath, int s) {
		File file = new File(imagePath);
		createDipPath(imagePath);
		FileOutputStream fOut = null;
		try {
			fOut = new FileOutputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		if (imagePath.toLowerCase().endsWith(".png")) {
			bitmap.compress(Bitmap.CompressFormat.PNG, s, fOut);
		} else if (imagePath.toLowerCase().endsWith(".jpg")) {
			bitmap.compress(Bitmap.CompressFormat.JPEG, s, fOut);
		} else {
			bitmap.compress(Bitmap.CompressFormat.WEBP, s, fOut);
		}
		try {
			fOut.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			fOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void copyFile(String sourcePath, String toPath) {
		File sourceFile = new File(sourcePath);
		File targetFile = new File(toPath);
		createDipPath(toPath);
		try {
			BufferedInputStream inBuff = null;
			BufferedOutputStream outBuff = null;
			try {
				inBuff = new BufferedInputStream(
						new FileInputStream(sourceFile));

				outBuff = new BufferedOutputStream(new FileOutputStream(
						targetFile));

				byte[] b = new byte[1024 * 5];
				int len;
				while ((len = inBuff.read(b)) != -1) {
					outBuff.write(b, 0, len);
				}
				outBuff.flush();
			} finally {
				if (inBuff != null)
					inBuff.close();
				if (outBuff != null)
					outBuff.close();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void copyFile(File sourceFile, File targetFile) {

		try {
			BufferedInputStream inBuff = null;
			BufferedOutputStream outBuff = null;
			try {
				inBuff = new BufferedInputStream(
						new FileInputStream(sourceFile));

				outBuff = new BufferedOutputStream(new FileOutputStream(
						targetFile));

				byte[] b = new byte[1024 * 5];
				int len;
				while ((len = inBuff.read(b)) != -1) {
					outBuff.write(b, 0, len);
				}
				outBuff.flush();
			} finally {
				if (inBuff != null)
					inBuff.close();
				if (outBuff != null)
					outBuff.close();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Bitmap compressImage(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 30, baos);
		int options = 100;
		while (baos.toByteArray().length / 1024 > 200) { 
			baos.reset();
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);
			options -= 10;
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
		return bitmap;
	}
	
	
    public Bitmap compressBySize(String pathName, int targetWidth,  
            int targetHeight) {  
        BitmapFactory.Options opts = new BitmapFactory.Options();  
        opts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);
        
        float imgWidth = opts.outWidth;  
        float imgHeight = opts.outHeight;  
        
        int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);  
        int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight); 
        opts.inSampleSize = 1;
        if (widthRatio > 1 || widthRatio > 1) {  
            if (widthRatio > heightRatio) {  
                opts.inSampleSize = widthRatio;  
            } else {  
                opts.inSampleSize = heightRatio;  
            }  
        }  
        
        opts.inJustDecodeBounds = false;  
        bitmap = BitmapFactory.decodeFile(pathName, opts);  
        return bitmap;  
    }
    
  
    public void saveFile(Bitmap bm, String fileName) throws Exception {
        File dirFile = new File(fileName);  
        
        if(dirFile.exists()){  
            dirFile.delete();  
        }  
        File myCaptureFile = new File(fileName);  
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));  
        
        bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);  
        bos.flush();  
        bos.close();  
    } 
    
    
    
    public static void saveImgtoPath(String path) {
    	Bitmap image = BitmapFactory.decodeFile(path);
    	ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		int options = 100;
		while (baos.toByteArray().length / 1024 > 100) { 
			baos.reset();
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		 File dirFile = new File(path);  
	  
	        if(dirFile.exists()){  
	            dirFile.delete();  
	        }  
	        File myCaptureFile = new File(path);  
	        BufferedOutputStream bos;
			try {
				bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
		        bos.flush();  
		        bos.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
	        
    	
    }

}
